{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "source": [
    "import torch\n",
    "import numpy as np\n",
    "import torch.nn as nn\n",
    "import torch.nn.functional as F\n",
    "from PIL import Image\n",
    "from torchvision import transforms\n",
    "from torchvision import models,datasets\n",
    "torch.__version__"
   ],
   "outputs": [
    {
     "output_type": "execute_result",
     "data": {
      "text/plain": [
       "'1.9.1+cu111'"
      ]
     },
     "metadata": {},
     "execution_count": 1
    }
   ],
   "metadata": {}
  },
  {
   "cell_type": "markdown",
   "source": [
    "tensorboard虽然是tensorflow内置的可视化工具，但是他们跑在不同的进程中，所以Github上已经有大神将tensorboard应用到Pytorch中 链接在这里\n",
    "Tensorboard 安装  \n",
    "首先需要安装tensorboard  \n",
    "\n",
    "pip install tensorboard  \n",
    "\n",
    "~~ 然后再安装tensorboardx ~~\n",
    "\n",
    "~~ pip install tensorboardx ~~ pytorch 1.1以后的版本内置了SummaryWriter 函数,所以不需要再安装tensorboardx了\n",
    "\n",
    "安装完成后与 visdom一样执行独立的命令 tensorboard --logdir logs 即可启动，默认的端口是 6006,在浏览器中打开 http://localhost:6006/ 即可看到web页面。\n",
    "\n",
    "这里要说明的是 微软的Edge浏览器css会无法加载，使用chrome正常显示"
   ],
   "metadata": {}
  },
  {
   "cell_type": "markdown",
   "source": [
    "页面  \n",
    "与visdom不同，tensorboard针对不同的类型人为的区分多个标签，每一个标签页面代表不同的类型。 下面我们根据不同的页面功能做个简单的介绍，更多详细内容请参考官网  \n",
    "SCALAR  \n",
    "对标量数据进行汇总和记录，通常用来可视化训练过程中随着迭代次数准确率(val acc)、损失值(train/test loss)、学习率(learning rate)、每一层的权重和偏置的统计量(mean、std、max/min)等的变化曲线  \n",
    "IMAGES  \n",
    "可视化当前轮训练使用的训练/测试图片或者 feature maps  \n",
    "GRAPHS  \n",
    "可视化计算图的结构及计算图上的信息，通常用来展示网络的结构  \n",
    "HISTOGRAMS  \n",
    "可视化张量的取值分布，记录变量的直方图(统计张量随着迭代轮数的变化情况）  \n",
    "PROJECTOR  \n",
    "全称Embedding Projector 高维向量进行可视化  \n"
   ],
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "source": [
    "\n",
    "# 这里的引用也要修改成torch的引用\n",
    "#from tensorboardX import SummaryWriter\n",
    "from torch.utils.tensorboard import SummaryWriter\n",
    "\n",
    "cat_img = Image.open('Felis_silvestris_catus_lying_on_rice_straw.jpg')\n",
    "cat_img.size\n",
    "transform_224 = transforms.Compose([\n",
    "        transforms.Resize(224), # 这里要说明下 Scale 已经过期了，使用Resize\n",
    "        transforms.CenterCrop(224),\n",
    "        transforms.ToTensor(),\n",
    "    ])\n",
    "cat_img_224=transform_224(cat_img)"
   ],
   "outputs": [],
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "source": [
    "writer = SummaryWriter(log_dir='./logs', comment='cat image') # 这里的logs要与--logdir的参数一样\n",
    "writer.add_image(\"cat\",cat_img_224)\n",
    "writer.close()# 执行close立即刷新，否则将每120秒自动刷新"
   ],
   "outputs": [],
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "source": [
    "\n",
    "x = torch.FloatTensor([100])\n",
    "y = torch.FloatTensor([500])\n",
    "\n",
    "for epoch in range(30):\n",
    "    x = x * 1.2\n",
    "    y = y / 1.1\n",
    "    loss = np.random.random()\n",
    "    with SummaryWriter(log_dir='./logs', comment='train') as writer: #可以直接使用python的with语法，自动调用close方法\n",
    "        writer.add_histogram('his/x', x, epoch)\n",
    "        writer.add_histogram('his/y', y, epoch)\n",
    "        writer.add_scalar('data/x', x, epoch)\n",
    "        writer.add_scalar('data/y', y, epoch)\n",
    "        writer.add_scalar('data/loss', loss, epoch)\n",
    "        writer.add_scalars('data/data_group', {'x': x,\n",
    "                                                'y': y}, epoch)"
   ],
   "outputs": [],
   "metadata": {}
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "source": [],
   "outputs": [],
   "metadata": {}
  }
 ],
 "metadata": {
  "interpreter": {
   "hash": "0bedf3452ed48e38a2b75ff9f66ce8ae9ae2e92e8665cb618ee0797d2f46b9e5"
  },
  "kernelspec": {
   "name": "python3",
   "display_name": "Python 3.8.10 64-bit ('d2l-zh': conda)"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.8.10"
  },
  "orig_nbformat": 4
 },
 "nbformat": 4,
 "nbformat_minor": 2
}